package com.hiss.basic.starter.core.utils;

import cn.hutool.extra.servlet.ServletUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ServletUtils {

    public static ServletRequestAttributes getRequestAttributes() {
        try {
            RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
            return (ServletRequestAttributes) attributes;
        } catch (Exception e) {
            return null;
        }
    }

    public static HttpServletRequest getRequest() {
        try {
            ServletRequestAttributes attributes = getRequestAttributes();
            if (null == attributes) {
                log.warn("Get request attributes is null");
                return null;
            }
            return attributes.getRequest();
        } catch (Exception e) {
            return null;
        }
    }

    public static HttpServletResponse getResponse() {
        try {
            ServletRequestAttributes attributes = getRequestAttributes();
            if (null == attributes) {
                log.warn("Get request attributes is null");
                return null;
            }
            return attributes.getResponse();
        } catch (Exception e) {
            return null;
        }
    }

    public static String getClientIP() {
        return ServletUtil.getClientIP(getRequest());
    }
}
